﻿using mozhi.smarterp.BasicData.Units.Service;
using Mozhi.Abp.Module.DataLinkage;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Guids;

namespace mozhi.smarterp.BasicData.Units
{
    public class UnitAppService : BasicDataAppService, IUnitAppService
    {
        private IUnitRepository _repository;
        private UnitManager _manager;
        private IGuidGenerator _guidGenerator;

        public UnitAppService(IUnitRepository repository, UnitManager manager, IGuidGenerator guidGenerator, IDataLinkageRepository dataLinkageRepository) : base(dataLinkageRepository)
        {
            _repository = repository;
            _manager = manager;
            _guidGenerator = guidGenerator;
        }

        public async Task<UnitDto> CreateAsync(UnitCreateDto input)
        {
            var unit = await _manager.CreateAsync(_guidGenerator.Create(), input.Code, input.Name, input.Activated);

            await _repository.InsertAsync(unit);

            return ObjectMapper.Map<Unit, UnitDto>(unit);
        }

        public async Task DeleteAsync(Guid id)
        {
            var count = await _dataLinkageRepository.GetCountAsync(null, id, null);

            if (count > 0)
                throw new UserFriendlyException("单位存在数据引用，无法删除" , BasicDataErrorCodes.DataLinkaged , id.ToString());

            await _repository.DeleteAsync(id);
        }

        public async Task<UnitDto> GetAsync(Guid id)
        {
            var unit = await _repository.GetAsync(id);

            return ObjectMapper.Map<Unit, UnitDto>(unit);
        }

        public async Task<PagedResultDto<UnitDto>> GetListAsync(PagedResultRequestDto filter)
        {
            var count = await _repository.GetCountAsync();

            var units = await _repository.GetPagedListAsync(filter.SkipCount, filter.MaxResultCount, "Code");

            return new PagedResultDto<UnitDto>()
            {
                TotalCount = count,
                Items = ObjectMapper.Map<List<Unit>, List<UnitDto>>(units)
            };
        }

        public async Task<UnitDto> UpdateAsync(UnitUpdateDto input)
        {
            var unit = await _manager.UpdateAsync(input.Id, input.Code, input.Name, input.Activated);

            await _repository.UpdateAsync(unit);

            return ObjectMapper.Map<Unit, UnitDto>(unit);
        }
    }
}
